#include "raft/context.h"

#include <stdlib.h>

#include "raft/raft.h"

namespace libraft {
Context::Context(const Options& options)
    : options_(options),
      voted_for_ip(""),
      voted_for_port(0),
      leader_ip(""),
      leader_port(0),
      vote_quorum(0),
      commit_index(0),
      last_applied(0),
      last_op_time(0) {}

Context::~Context() {}

void Context::RecoverInit(const std::shared_ptr<Meta>& meta) {
  current_term = meta->GetCurrentTerm();
  voted_for_port = meta->GetVotedForPort();
  voted_for_ip = meta->GetVotedForIp();
  commit_index = meta->GetCommitIndex();
  last_applied = meta->GetLastApplied();
  role = Role::kFollower;
}

void Context::BecomeFollower(uint64_t new_term, const std::string _leader_ip,
                             int _leader_port) {
  current_term = new_term;
  leader_ip = _leader_ip;
  leader_port = _leader_port;
  role = Role::kFollower;
}

void Context::BecomeCandidate() {
  current_term++;
  role = Role::kCandidate;
  leader_ip.clear();
  leader_port = 0;
  voted_for_port = options_.local_port;
  voted_for_ip = options_.local_ip;
  vote_quorum = 1;
}

void Context::BecomeLeader() {
  role = Role::kLeader;
  leader_ip = options_.local_ip;
  leader_port = options_.local_port;
}

}  // namespace libraft